package web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bl.GameManager;

import com.google.gson.JsonObject;

import objects.Board;
import objects.BoardData;
import objects.ConfigurationType;
import objects.Player;
import utils.FactoryUI;

/**
 * Servlet implementatio
 * n class JoinServlet
 */
@WebServlet(name = "Join", urlPatterns =
{
    "/Join"
})
public class JoinServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static List<String> joined;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public JoinServlet() 
    {
    	super();
    	joined = new ArrayList<String>();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String joinedPlayer = request.getParameter("browserPlayer");
		String creator = request.getParameter("creator");
		
		/*if (Board.getInstance().getNumberOfPlayersJoined() == 0)
		{
			Board.getInstance().backUp();
		}*/
		if (creator != null && !creator.equals("null"))
		{
			request.setAttribute("creator", Boolean.parseBoolean(creator));
		}
		
		boolean isValid = true;
		
		if (joinedPlayer == null || joinedPlayer == "")
		{
			request.setAttribute("errorMsg", "You must insert a name!");
			isValid = false;
		}
		else if (Board.getInstance().getBdGameData().getType().equals(ConfigurationType.MANUAL))
		{
			for (int i = 0; i < Board.getInstance().getNumberOfPlayersJoined(); i++) {
				if (Board.getInstance().getBdGameData().getPlayerByIndex(i).getPlayerName().equals(joinedPlayer))
				{
					request.setAttribute("errorMsg", "The name is already taken!");
					isValid = false;
					break;
				}
			}
		}
		
		if (!isValid)
		{
			request.setAttribute("pageName", "newGame"); 
	    	// Call index.jsp (the page to call was set by pageName on the jsp)
	    	RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
	    	dispatcher.forward(request, response);
		}
		else
		{
			Player joinedInstancePlayer = null;
			
			if (Board.getInstance().getBdGameData().getType().equals(ConfigurationType.MANUAL))
			{
				joinedInstancePlayer = Board.getInstance().getBdGameData().getPlayerByIndex(Board.getInstance().getNumberOfPlayersJoined());
			}
			else
			{
				joinedInstancePlayer = Board.getInstance().getPlayerByName(joinedPlayer);
				
				if (joinedInstancePlayer.isOccupied())
				{
					request.setAttribute("errorMsg", "The name is already taken!");
					request.setAttribute("pageName", "newGame"); 
			    	// Call index.jsp (the page to call was set by pageName on the jsp)
			    	RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
			    	dispatcher.forward(request, response);
			    	return;
				}
			}
			
			joinedInstancePlayer.setPlayerName(joinedPlayer);
			joinedInstancePlayer.setOccupied(true);
			Board.getInstance().setNumberOfPlayersJoined(Board.getInstance().getNumberOfPlayersJoined() + 1);
			
			int nWait = 0;
			if (Board.getInstance().getNumberOfPlayersJoined() < Board.getInstance().getBdGameData().getPlayers().size())
			{
				nWait = 1;
				
			}
			
			if (nWait == 0)
			{
				Board.getInstance().backUp();
			}
			JsonObject jsAction = new JsonObject();
			jsAction.addProperty("code", "join");
			jsAction.addProperty("player", joinedPlayer);
			
			if (nWait == 0)
			{
				jsAction.addProperty("lastPlayer", joinedPlayer);
			}
			else
			{
				jsAction.addProperty("lastPlayer", "");
			}
			
			jsAction.addProperty("playerType", joinedInstancePlayer.getType());
			jsAction.addProperty("currentPlayerType", Board.getInstance().getCurrPlayerInstance().getType());
			jsAction.addProperty("waitformore", nWait);
			jsAction.addProperty("message", "Player " +joinedPlayer+ " has joined the game!");
			Board.getInstance().addJsActions(jsAction);
			
			request.setAttribute("pageName", "game"); 
			request.setAttribute("playerID", joinedPlayer); 
	    	// Call index.jsp (the page to call was set by pageName on the jsp)
	    	RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
	    	dispatcher.forward(request, response);
	    	
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		String joinedPlayer = request.getParameter("browserPlayer");
		String creator = request.getParameter("creator");
		PrintWriter out = response.getWriter();
		out.flush();
		if (creator != null && !creator.equals("null"))
		{
			request.setAttribute("creator", Boolean.parseBoolean(creator));
		}
		
		boolean isValid = true;
		if (joinedPlayer == null || joinedPlayer == "")
		{
			request.setAttribute("errorMsg", "You must insert a name!");
			isValid = false;
		}
		else if (Board.getInstance().getBdGameData().getType().equals(ConfigurationType.MANUAL))
		{
			for (int i = 0; i < Board.getInstance().getNumberOfPlayersJoined(); i++) {
				if (Board.getInstance().getBdGameData().getPlayerByIndex(i).getPlayerName().equals(joinedPlayer))
				{
					request.setAttribute("errorMsg", "The name is already taken!");
					isValid = false;
					break;
				}
			}
		}
		
		if (!isValid)
		{
			request.setAttribute("pageName", "newGame"); 
	    	// Call index.jsp (the page to call was set by pageName on the jsp)
		}
		else
		{
			Player joinedInstancePlayer = null;
			
			if (Board.getInstance().getBdGameData().getType().equals(ConfigurationType.MANUAL))
			{
				joinedInstancePlayer = Board.getInstance().getBdGameData().getPlayerByIndex(Board.getInstance().getNumberOfPlayersJoined());
			}
			else
			{
				joinedInstancePlayer = Board.getInstance().getPlayerByName(joinedPlayer);
				
				if (joinedInstancePlayer.isOccupied())
				{
					request.setAttribute("errorMsg", "The name is already taken!");
					request.setAttribute("pageName", "newGame"); 
			    	// Call index.jsp (the page to call was set by pageName on the jsp)
			    	RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
			    	dispatcher.forward(request, response);
			    	return;
				}
			}
			
			joinedInstancePlayer.setPlayerName(joinedPlayer);
			joinedInstancePlayer.setOccupied(true);
			Board.getInstance().setNumberOfPlayersJoined(Board.getInstance().getNumberOfPlayersJoined() + 1);
			
			int nWait = 0;
			if (Board.getInstance().getNumberOfPlayersJoined() < Board.getInstance().getBdGameData().getPlayers().size())
			{
				nWait = 1;
			}

			if (nWait == 0)
			{
				Board.getInstance().resetActions();
			}
			
			if (!joined.contains(joinedPlayer))
			{
				joined.add(joinedPlayer);
				JsonObject jsAction = new JsonObject();
				jsAction.addProperty("toMove", "yes");
				out.print(jsAction);
			}
			
			JsonObject jsAction = new JsonObject();
			jsAction.addProperty("code", "join");
			jsAction.addProperty("player", joinedPlayer);
			
			jsAction.addProperty("waitformore", nWait);
			jsAction.addProperty("message", "Player " +joinedPlayer+ " has joined the game!");
			Board.getInstance().addJsActions(jsAction);
			
			request.setAttribute("pageName", "game"); 
			request.setAttribute("playerID", joinedPlayer); 
	    	// Call index.jsp (the page to call was set by pageName on the jsp)
		}
	}
}
